//
//  TWAnimationHeaderView.swift
//  EyepetizerImitative
//
//  Created by 田伟 on 2017/4/5.
//  Copyright © 2017年 个人. All rights reserved.
//

import UIKit
import SnapKit

let LineSpaceing : CGFloat = 5.0
let TopViewHeight : CGFloat = 50
let Margin : CGFloat = 10


class TWAnimationHeaderView: UIView {

    // 背景
    fileprivate lazy var backgroundView: UIView = UIView()
    // 上部分
    fileprivate lazy var topView: UIView = UIView()
    fileprivate lazy var topView_titleLabel: UILabel = UILabel()
    fileprivate lazy var topView_timeLabel: UILabel = UILabel()
    fileprivate lazy var topView_showMoreButton: UIButton = UIButton()
    fileprivate lazy var topView_detailLabel: UILabel = UILabel()
    // 中间
    fileprivate lazy var middleView: UIView = UIView()
    fileprivate lazy var lineViewLabel: UILabel = UILabel()
    fileprivate lazy var middleView_titleLabel: UILabel = UILabel()
    fileprivate lazy var middleView_detailLabel: UILabel = UILabel()
    // 工具条
    fileprivate lazy var toolView: UIView = UIView()
    fileprivate lazy var toolView_likeButton: toolViewButton = toolViewButton()
    fileprivate lazy var toolView_shareButton: toolViewButton = toolViewButton()
    fileprivate lazy var toolView_reviewButton: toolViewButton = toolViewButton()
    fileprivate lazy var toolView_daowloadButton: toolViewButton = toolViewButton()
    fileprivate lazy var toolView_lineViewLabel: UILabel = UILabel()
    // 底部
    fileprivate lazy var bottomView: UIView = UIView()
    fileprivate lazy var bottomView_iconImageView: UIImageView = UIImageView()
    fileprivate lazy var bottomView_nameLabel: UILabel = UILabel()
    fileprivate lazy var bottomView_descriptionLabel: UILabel = UILabel()
    fileprivate lazy var bottomView_attentionButton: UIButton = UIButton()
    fileprivate lazy var bottomView_lineViewLabel: UILabel = UILabel()
    
    var itemModel : TWItemModel?{
        didSet {
            headerHeight = 0
            guard let itemModel = itemModel else {
                return
            }
            
            // 顶部
            topView_titleLabel.text = itemModel.title
            topView_timeLabel.text = "#\(itemModel.category!)" + " / " + "\(itemModel.duration_tw!)"
            headerHeight += TopViewHeight           
            headerHeight += Margin
            // 详情
            let descriptionEditor = itemModel.descriptionEditor
            if let descriptionEditor = descriptionEditor {
                let topView_detailLabelHeight = calculateBoundingRectHeight(label: topView_detailLabel, string: descriptionEditor)
                headerHeight += topView_detailLabelHeight
            }else {
                headerHeight += 0   
            }
            headerHeight += Margin
            headerTopViewHeight = headerHeight
            
            // 中间
            let descriptionPgc = itemModel.descriptionPgc
            if let descriptionPgc = descriptionPgc {
                if descriptionPgc.characters.count != 0 {
                    
                    // MARK:- 暂时将这个按钮隐藏
//                    topView_showMoreButton.isHidden = false
                    
                }else {
                    topView_showMoreButton.isHidden = true
                }
            } else {
                print("没有descriptionPgc这个对象")
            }
            
            toolView.snp.makeConstraints { (make) in
                make.top.equalTo(self).offset(headerTopViewHeight)
            }
            
            toolView_likeButton.setTitle((itemModel.consumption?.collectionCount)?.stringValue, for: .normal)
            toolView_shareButton.setTitle((itemModel.consumption?.shareCount)?.stringValue, for: .normal)
            toolView_reviewButton.setTitle((itemModel.consumption?.replyCount)?.stringValue, for: .normal)
            headerHeight += 44
            
            // 背景
            backgroundView.snp.makeConstraints { (make) in
                make.left.right.top.equalTo(self)
                make.bottom.equalTo(toolView.snp.bottom)
            }
            
            // 底部
            if itemModel.author == nil {
                // 无作者信息
                bottomView.isHidden = true
                headerHeight += 0
            } else {
                // 有作者信息
                headerHeight += 80
                bottomView.isHidden = false
                bottomView_iconImageView.sd_setImage(with: URL(string: (itemModel.author?.icon)!))
                bottomView_nameLabel.text = itemModel.author?.name
                bottomView_descriptionLabel.text = itemModel.author?.tw_description
            }
        }
    }
    var headerHeight : CGFloat = 0
    var headerTopViewHeight : CGFloat = 0
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupbackgroundView()
        setupTopView()
        setupToolView()
        setupBottomView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK:- 监听点击
extension TWAnimationHeaderView {
    @objc fileprivate func topView_showMoreButtonDidClick(button : UIButton){
        setupMiddleView()
        
        let descriptionPgc = itemModel?.descriptionPgc
        middleView_titleLabel.text = itemModel?.title
        let middleView_detailLabelHeight = calculateBoundingRectHeight(label: middleView_detailLabel, string: descriptionPgc!)
        
        if button.isSelected {
            // 增加中间的东西
            middleView.isHidden = false
            middleView_titleLabel.isHidden = false
            middleView_detailLabel.isHidden = false
            lineViewLabel.isHidden = false
            // middleView的总高度
            let middleHeight =  middleView_detailLabelHeight + middleView_titleLabel.font.lineHeight + Margin * 3
            let toolViewMove = headerTopViewHeight + middleHeight
            UIView.animate(withDuration: 0.5, animations: {
                self.topView_showMoreButton.imageView?.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                self.headerHeight += middleHeight
                self.toolView.snp.updateConstraints({ (make) in
                    make.top.equalTo(self).offset(toolViewMove)
                })
            })
            button.isSelected = false
        } else {
            middleView.isHidden = true
            middleView_titleLabel.isHidden = true
            middleView_detailLabel.isHidden = true
            lineViewLabel.isHidden = true
            let middleHeight =  middleView_detailLabelHeight + middleView_titleLabel.font.lineHeight + Margin * 3
            UIView.animate(withDuration: 0.5, animations: {
                self.topView_showMoreButton.imageView?.transform = CGAffineTransform.identity
                self.headerHeight -= middleHeight
                self.toolView.snp.updateConstraints({ (make) in
                    make.top.equalTo(self).offset(self.headerTopViewHeight)
                })
            })
            button.isSelected = true
        }
        NotificationCenter.default.post(name: NSNotification.Name(rawValue :AnimationHeaderViewShowMoreButtonClickNotification), object: nil)
    }
}



// MARK:- UI界面
extension TWAnimationHeaderView {
    fileprivate func setupbackgroundView(){
        backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        addSubview(backgroundView)
    }
    fileprivate func setupTopView(){
        addSubview(topView)
        topView.snp.makeConstraints { (make) in
            make.left.top.right.equalTo(self)
            make.height.equalTo(TopViewHeight)
        }
        topView_showMoreButton.setImage(UIImage(named: "Action_down_44x44_"), for: .normal)
        topView_showMoreButton.addTarget(self, action: #selector(topView_showMoreButtonDidClick(button:)), for: .touchUpInside)
        topView_showMoreButton.isHidden = true
        topView_showMoreButton.isSelected = true
        topView.addSubview(topView_showMoreButton)
        topView_showMoreButton.snp.makeConstraints { (make) in
            make.width.height.equalTo(44)
            make.right.equalTo(topView)
            make.centerY.equalTo(topView)
        }
        topView_titleLabel.textColor = UIColor.white
        topView_titleLabel.font = UIFont(name: "FZLTZCHJW--GB1-0", size: 17)
        topView.addSubview(topView_titleLabel)
        topView_titleLabel.snp.makeConstraints { (make) in
            make.top.left.equalTo(topView).offset(Margin)
            make.right.equalTo(topView_showMoreButton.snp.left).offset(-Margin)
        }
        topView_timeLabel.textColor = topView_titleLabel.textColor
        topView_timeLabel.font = UIFont(name: "FZLTXIHJW--GB1-0", size: 14)
        topView.addSubview(topView_timeLabel)
        topView_timeLabel.snp.makeConstraints { (make) in
            make.left.right.equalTo(topView_titleLabel)
            make.bottom.equalTo(topView)
        }
        topView_detailLabel.textColor = topView_titleLabel.textColor
        topView_detailLabel.numberOfLines = 0
        addSubview(topView_detailLabel)
        topView_detailLabel.snp.makeConstraints { (make) in
            make.left.equalTo(topView).offset(Margin)
            make.right.equalTo(topView).offset(-Margin)
            make.top.equalTo(topView.snp.bottom).offset(Margin)
        }
    }
    fileprivate func setupMiddleView(){
        let descriptionPgc = itemModel?.descriptionPgc
        middleView_titleLabel.text = itemModel?.title
        let middleView_detailLabelHeight = calculateBoundingRectHeight(label: middleView_detailLabel, string: descriptionPgc!)
        // middleView的总高度
        let middleHeight = middleView_detailLabelHeight + Margin + middleView_titleLabel.font.lineHeight + Margin * 2
        
        addSubview(middleView)
        middleView.isHidden = true
        middleView.snp.makeConstraints { (make) in
            make.left.right.equalTo(self)
            make.top.equalTo(self).offset(headerTopViewHeight)
            make.height.equalTo(middleHeight)
        }
        
        lineViewLabel.backgroundColor = UIColor.white.withAlphaComponent(0.25)
        lineViewLabel.isHidden = true
        middleView.addSubview(lineViewLabel)
        lineViewLabel.snp.makeConstraints { (make) in
            make.top.equalTo(middleView)
            make.left.equalTo(middleView).offset(Margin)
            make.right.equalTo(self)
            make.height.equalTo(1)
        }
        
        middleView_titleLabel.textColor = UIColor.white
        middleView_titleLabel.font = UIFont(name: "FZLTZCHJW--GB1-0", size: 15)
        middleView.addSubview(middleView_titleLabel)
        middleView_titleLabel.snp.makeConstraints { (make) in
            make.left.right.equalTo(middleView).offset(Margin)
            make.top.equalTo(lineViewLabel.snp.bottom).offset(Margin)
        }
        middleView_detailLabel.textColor = middleView_titleLabel.textColor
        middleView_detailLabel.backgroundColor = UIColor.clear
        middleView_detailLabel.textAlignment = .left
        middleView_detailLabel.numberOfLines = 0
        middleView.addSubview(middleView_detailLabel)
        middleView_detailLabel.snp.makeConstraints { (make) in
            make.left.equalTo(middleView).offset(Margin)
            make.right.equalTo(middleView).offset(-Margin)
            make.top.equalTo(middleView_titleLabel.snp.bottom).offset(Margin)
        }
    }
    fileprivate func setupToolView(){
        addSubview(toolView)
        toolView.snp.makeConstraints { (make) in
            make.left.right.equalTo(self)
            make.height.equalTo(44)
        }
        toolView_likeButton.setImage(UIImage(named: "Action_Like_44x44_"), for: .normal)
        toolView.addSubview(toolView_likeButton)
        toolView_likeButton.snp.makeConstraints { (make) in
            make.left.equalTo(topView)
            make.centerY.equalTo(toolView)
        }
        toolView_shareButton.setImage(UIImage(named: "Action_Share_44x44_"), for: .normal)
        toolView.addSubview(toolView_shareButton)
        toolView_shareButton.snp.makeConstraints { (make) in
            make.left.equalTo(toolView_likeButton.snp.right).offset(Margin * 2)
            make.centerY.equalTo(toolView)
        }
        toolView_reviewButton.setImage(UIImage(named: "Action_review_44x44_"), for: .normal)
        toolView.addSubview(toolView_reviewButton)
        toolView_reviewButton.snp.makeConstraints { (make) in
            make.left.equalTo(toolView_shareButton.snp.right).offset(Margin * 2)
            make.centerY.equalTo(toolView)
        }
        toolView_daowloadButton.setImage(UIImage(named: "Action_download_44x44_"), for: .normal)
        toolView_daowloadButton.setTitle("缓存", for: .normal)
        toolView.addSubview(toolView_daowloadButton)
        toolView_daowloadButton.snp.makeConstraints { (make) in
            make.left.equalTo(toolView_reviewButton.snp.right).offset(Margin * 2)
            make.centerY.equalTo(toolView)
        }
        toolView_lineViewLabel.backgroundColor = UIColor.white.withAlphaComponent(0.25)
        toolView.addSubview(toolView_lineViewLabel)
        toolView_lineViewLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(toolView.snp.bottom).offset(1)
            make.left.right.equalTo(self)
            make.height.equalTo(1)
        }
    }
    fileprivate func setupBottomView(){
        addSubview(bottomView)
        bottomView.snp.makeConstraints { (make) in
            make.left.right.equalTo(self)
            make.top.equalTo(toolView.snp.bottom)
            make.height.equalTo(80)
        }
        bottomView_iconImageView.layer.cornerRadius = 30
        bottomView_iconImageView.layer.masksToBounds = true
        bottomView.addSubview(bottomView_iconImageView)
        bottomView_iconImageView.snp.makeConstraints { (make) in
            make.width.height.equalTo(60)
            make.centerY.equalTo(bottomView)
            make.left.equalTo(bottomView).offset(Margin)
        }
        bottomView_attentionButton.setTitle("+关注", for: .normal)
        bottomView_attentionButton.titleLabel?.font = UIFont(name: "FZLTZCHJW--GB1-0", size: 12)
        // 添加边框
        bottomView_attentionButton.layer.masksToBounds = true
        bottomView_attentionButton.layer.cornerRadius = 4
        bottomView_attentionButton.layer.borderWidth = 1
        bottomView_attentionButton.layer.borderColor = UIColor.white.cgColor
        bottomView.addSubview(bottomView_attentionButton)
        bottomView_attentionButton.snp.makeConstraints { (make) in
            make.centerY.equalTo(bottomView)
            make.right.equalTo(bottomView).offset(-Margin)
            make.width.equalTo(40)
            make.height.equalTo(17)
        }
        bottomView_nameLabel.textColor = UIColor.white
        bottomView_nameLabel.font = UIFont(name: "FZLTZCHJW--GB1-0", size: 14)
        bottomView.addSubview(bottomView_nameLabel)
        bottomView_nameLabel.snp.makeConstraints { (make) in
            make.left.equalTo(bottomView_iconImageView.snp.right).offset(Margin)
            make.right.equalTo(bottomView_attentionButton.snp.left).offset(-Margin)
            make.centerY.equalTo(bottomView).offset(-Margin)
        }
        bottomView_descriptionLabel.textColor = UIColor.white
        bottomView_descriptionLabel.font = UIFont(name: "FZLTXIHJW--GB1-0", size: 13)
        bottomView.addSubview(bottomView_descriptionLabel)
        bottomView_descriptionLabel.snp.makeConstraints { (make) in
            make.left.equalTo(bottomView_iconImageView.snp.right).offset(Margin)
            make.right.equalTo(bottomView_attentionButton.snp.left).offset(-Margin)
            make.centerY.equalTo(bottomView).offset(Margin)
        }
        bottomView_lineViewLabel.backgroundColor = UIColor.white.withAlphaComponent(0.25)
        bottomView.addSubview(bottomView_lineViewLabel)
        bottomView_lineViewLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(bottomView)
            make.right.left.equalTo(self)
            make.height.equalTo(1)
        }
    }
}

// MARK:- 计算属性
extension TWAnimationHeaderView {
    fileprivate func calculateBoundingRectHeight(label : UILabel, string : String) -> CGFloat {
        // 根据文本计算是否需要增加行间距
        let attributedString : NSMutableAttributedString = NSMutableAttributedString(string: string)
        let font = UIFont(name: "FZLTXIHJW--GB1-0", size: 14)
        label.font = font
        let paragraphStyle : NSMutableParagraphStyle = NSMutableParagraphStyle()
        attributedString.addAttributes([NSParagraphStyleAttributeName : paragraphStyle, NSFontAttributeName : font!], range: NSRange(location: 0, length: (string.characters.count)))
        
        // 计算是否超过一行
        if (attributedString.string as NSString).isMoreThanOneLine(with: CGSize(width: UIScreen.main.bounds.width - 20, height: CGFloat(MAXFLOAT)), font: font, lineSpaceing: LineSpaceing) {
            // 超过一行才设置行距
            paragraphStyle.lineSpacing = LineSpaceing
        }
        // 赋值
        label.attributedText = attributedString
        label.sizeToFit()
        // 计算高度
        let boundingRectHeight = (attributedString.string as NSString).boundingRect(with: CGSize(width: UIScreen.main.bounds.width - 20, height: CGFloat(MAXFLOAT)), font: font!, lineSpacing: LineSpaceing).height
        return boundingRectHeight
    }
}

// 统一按钮的样式
class toolViewButton: UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)
        titleLabel?.font = UIFont(name: "FZLTXIHJW--GB1-0", size: 14)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: -5, bottom: 0, right: 0)
        imageEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
